#coding:utf-8
from  django.shortcuts  import  render_to_response
from django.shortcuts import render 
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.http import HttpResponseRedirect
from django.http import HttpResponse

from django.db.models import Q


from django.contrib import auth

from jobs.models import Project,Task

from django.forms import Form
from django import forms
from project import models
#from datetime import datetime
import datetime
from django.contrib.auth.models import User


@csrf_protect
def Login(request,template_file):
    #c.update(csrf(request))
    if request.method=="POST":
        user = auth.authenticate(username=request.POST.get("username",""), password=request.POST.get("password",""))
        if user is not None:
            auth.login(request, user)
            return HttpResponseRedirect("/jobs" )
        else:
            error = "用户名或密码错误"
            
        return render(request,template_file ,locals())
        
    else:
        return render(request, template_file,locals())

def Logout(request):
    auth.logout(request)
    return HttpResponseRedirect("/login" )
    

##修改基本信息
class changeUserInfoForm(Form): 
    last_name = forms.CharField(label="姓氏",max_length=30,widget=forms.TextInput(attrs={'size': 20,})) 
    first_name = forms.CharField(label="名字",max_length=30,widget=forms.TextInput(attrs={'size': 20,})) 
    email = forms.CharField(label="用户邮箱",max_length=30,widget=forms.EmailField())


@login_required
@csrf_protect
def EditUserInfo(request , template_file):
    project_list = Project.objects.all()
    user = request.user
    if request.method=="POST": 
        user.first_name = request.POST.get("first_name")
        user.last_name = request.POST.get("last_name")
        user.email = request.POST.get("email")
        user.save()
        word = "修改成功!"
    return render(request, template_file, locals() )
    
    
    




class changepasswordForm(Form): 
    oldpassword = forms.CharField(label="原口令",max_length=30,widget=forms.PasswordInput(attrs={'size': 20,})) 
    newpassword = forms.CharField(label="新口令",max_length=30,widget=forms.PasswordInput(attrs={'size': 20,})) 
    newpassword1 = forms.CharField(label="新口令确认",max_length=30,widget=forms.PasswordInput(attrs={'size': 20,}))

@login_required
@csrf_protect
def ChangePassword(request , template_file):
    form = changepasswordForm()    
    project_list = Project.objects.all()
    
    
    if request.method=="POST": 
            form = changepasswordForm(request.POST.copy()) 
            if form.is_valid(): 
                username = request.user.username 
                oldpassword = form.cleaned_data["oldpassword"] 
                newpassword = form.cleaned_data["newpassword"] 
                newpassword1 = form.cleaned_data["newpassword1"] 
                user = auth.authenticate(username=username,password=oldpassword) 
                if user: #原口令正确 
                    if newpassword == newpassword1:#两次新口令一致 
                        user.set_password(newpassword) 
                        user.save() 
                        word = '密码修改成功!!' 
                    else:#两次新口令不一致 
                        word = '两次输入口令不一致'   
                else:  #原口令不正确 
                    if newpassword == newpassword1:#两次新口令一致 
                        word = '原口令不正确'   
                    else:#两次新口令不一致 
                        word = '原口令不正确，两次输入口令不一致'   
                        
    return render(request, template_file, locals())
    
#from django.core.mail import send_mail
from django.core.mail import EmailMultiAlternatives
from datetime import timedelta
@login_required
@csrf_protect
def UserReport( request  ,typ, template_file):
    if request.user.username != "gao":
        return HttpResponseRedirect("/jobs")
        
    if request.method=="POST":
        userlist = User.objects.filter(is_active= True )
        mails=[]
        for user in userlist:
            if user.email!=None:
                mails.append(user.email)
        msg = EmailMultiAlternatives(request.POST.get("title") , u"这是一封html版本邮件。", request.user.email, mails  )
        msg.attach_alternative(request.POST.get("content") , "text/html")
        msg.send()
        
        return HttpResponse("success")
    project_list = Project.objects.all()
    
    dt = datetime.datetime.now()
    a = request.GET.get("sub",0)
    
    dt = dt+timedelta(days=int(a) ) 
    if typ == "day":
        typ = u"日报"
        now_page = u"今日"
        next_page = u"明日"
        title = u"%s-%s" % (typ, dt.strftime(" %Y%m%d ") )
        now_task_list = Task.objects.filter( state__range=[2,4]  , edit__year=dt.strftime("%Y") , edit__month=dt.strftime("%m") , edit__day=dt.strftime("%d")).order_by("-user") #filter().filter(edit__)
        next_task_list = Task.objects.filter( Q(state = 2 ) | Q(start_date = dt + datetime.timedelta(1) )  ).order_by("-user")


    else:
        typ =u"周报"
        now_page = u"本周"
        next_page = u"下周"
        title = u"%s-%s" % (typ, dt.strftime(" %Y%m%d ") )
        '''

        计算一个日期是星期几，可以依据蔡勒公式：
        w=y+[y/4]+[c/4]-2c+[26(m+1)/10]+d-1
        其中：
        w % 7 = 0-星期日，1-星期一，2-星期二，3-星期三，4-星期四，5-星期五，6-星期六
        y = YYYY的后2位，比如1989的89
        c = YYYY的前2位，比如1989的19
        m = MM，但是3<=m<=14，在蔡勒公式中，某年的1、2月要看作上一年的13、14月来计算，比如1989年01月要看作1988年的13月
        d = DD，比如01
        []表示取整
        '''
        this_weekday_start = dt - datetime.timedelta(dt.weekday())
        this_weekday_end = dt - datetime.timedelta(6-dt.weekday())
        
        next_weekday_start = dt- datetime.timedelta(7-dt.weekday())
        next_weekday_start = dt- datetime.timedelta(13-dt.weekday())
        
        now_task_list = Task.objects.filter(state__in=[2,4] , edit__gte=this_weekday_start  , edit__lte=this_weekday_end ).order_by("-user")
        next_task_list = Task.objects.filter(state__in=[1,2] , edit__gte=next_weekday_start  , edit__lte=next_weekday_start ).order_by("-user")
    
    all_list = Task.objects.filter(is_bug=0,state__range=[1,3] ).order_by("-start_date")
    bug_list = Task.objects.filter(is_bug=1,state__range=[1,3] ).order_by("-start_date")
    
    #not_run = len(Task.objects.filter(is_bug=0 ).filter(state=1))
    #runing = len(Task.objects.filter(is_bug=0 ).filter(state=2))
    not_run=0
    runing =0
    later_run = 0
    overs = 0
    for task_tmp in all_list:
        if task_tmp.state == 1 : not_run +=1 
        if task_tmp.state == 2:runing+=1 
        if task_tmp.state==3 :later_run+=1 
        if task_tmp.state == 4 :overs+=1 
        
    import matplotlib.pyplot as plt
    import matplotlib.font_manager as font_manager
    import numpy
    import base64
    import cStringIO
    __f__ = cStringIO.StringIO()
    import sys
    
    font = font_manager.FontProperties(family="sans-serif", fname='./font.ttf',size=14)
    font8 = font_manager.FontProperties(family="sans-serif", fname='./font.ttf',size=8.5)
    
    # font_manager.FontProperties(family="sans-serif", fname='./font.ttf',size=14)
    labels = u'未开始(%d)' % not_run , u'处理中(%d)' % runing , u'推迟(%d)' % later_run, u'已完成(%d)' % overs
    sizes = [not_run, runing, later_run, overs]
    colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
    explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
    # plt.rcParams['font.sans-serif'] = ["Microsoft YaHei"]
    plt.rcParams['font.size']=8.5
    ax = plt.figure(figsize = (3.5,3.4 ) )
    
    ax.suptitle(u'任务类型占比', fontsize=14,fontproperties=font)
    
    patches, labels_text, autotexts =plt.pie(sizes, explode=explode, labels=labels, colors=colors,
            autopct='%1.1f%%', shadow=True)
    for te in labels_text:
        te.set_fontproperties(font8)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.savefig(__f__)
    polt_by_all_task_state = base64.b64encode(__f__.getvalue())
    __f__.close()
    plt.close()
    
    return render(request,template_file,locals() )

        
    
